Vue.directive('select2', {
    deep: true,
    twoWay: true,
    params: ['select2Param', 'customstyle', 'url', 'useData', 'callback', 'query', 'templateresult'],

    bind: function() {
        var self = this;
        var option=$.extend({}, self.params.customstyle)
        if (self.params.url !== undefined) {
            var type=$(self.el).data("segtype");
            option.ajax = {
                url: self.params.url,
                dataType: 'json',
                delay: 250,
                data: function (data) {
                    if (self.params.query !== undefined) {
                        var result = self.params.query(data);
                        return result;
                    }
                    else {
                        return {
                            type: type,
                            value: data.term,
                        };
                    }
                },
                escapeMarkup: function (m) {
                    return m;
                },
                processResults: function (data) {
                    if (self.params.callback != undefined) {
                        var result = self.params.callback(data);
                        return result;
                    }
                    else {
                        var array = [];
                        for (var i = 0; i < data.Data.EbsSeg.length; i++) {
                            array.push({ "id": data.Data.EbsSeg[i].VALUE4, "text": data.Data.EbsSeg[i].VALUE5 });
                        }
                        return {
                            results: array
                        };
                    }
                }
                ,
                cache: true
            };
            option.templateResult = function (item) {
                if (self.params.templateresult !== undefined) {
                    var result = self.params.templateresult(item);
                    return result;
                }
                else {
                    if (item && item.id !== undefined && item.text !== undefined && item.id !== null && item.text != null) {
                        return item.id + ' ' + item.text;
                    }
                    else if (item && typeof item.disabled !== undefined) {
                        return item.text;
                    }
                    else
                        return '';
                }
            }
        }

        $(this.el)
            .select2(option)
            .on('change', function() {
                self.set(this.value);
            });
    },
    update: function (value) {
        $(this.el).val(value).trigger('change');
    },
    unbind: function() {
        $(this.el).off().select2('destroy');
    }
});